<?php 
namespace Common\Model;

use Org\Wechat\WechatAuth;
/**
 * 关注
 * @author lanxuebao
 *
 */
class GuanzhuModel extends BaseModel{
    protected $tableName = 'member';
    
    /**
     * 绑定 推荐人 和 被推荐人,如果被推荐人是第一次进入平台，则给推荐人1毛钱
     * 本方法返回的值都用于wechatController
     * @param unknown $user
     * @param unknown $shareMember
     */
    public function shareGuanzhu($user, $share_mid){
        if(empty($user['id'])){
            $this->error = '数据不存在！！';
            return -1;
        }else if($user['agent_level'] > 0){
            $this->error = '您已成为代理，无需绑定上级好友';
            return -1;
        }else if($user['id'] == $share_mid){
            $this->error = '您不能绑定您自己！';
            return -1;
        }else if($user['pid'] == $share_mid){
            $this->error = '您已与推荐人为好友关系!';
            return -1;
        }else if($user['pid'] > 0){
            $this->error = '不可重新绑定推荐人！';
            return -1;
        }
        
        //查询分享人信息
        $shareMember = $this->getWXUserConfig($share_mid);
        if(empty($shareMember)){
            $this->error = '暂无数据，请确认扫描的二维码属于您的推荐人';
            return -1;
        }else if($shareMember['pid'] == $user['id']){
            $this->error = '推荐人为您的下级好友，无法进行绑定！';
            return -1;
        }
        
        //验证分享人是否是登录人的下线
        $is_my_child = $this->query("select isMyChild({$shareMember['id']},{$user['id']}) AS is_my_child");
        if($is_my_child[0]["is_my_child"] != 0){
            $this->error = '绑定失败，上下级关系为死循环';
            return -1;
        }
    
        $this->execute("UPDATE member SET pid=".$shareMember['id']." WHERE id=".$user['id']);
        
        if(!empty($shareMember['config'])){
            $content = '【'.$user['nickname'].'】已成为您的好友！';
            $wechatAuth = new WechatAuth($shareMember['config']['WEIXIN']);
            $wechatAuth->messageCustomSend($shareMember['openid'], $content);
        }
        
        return $shareMember;
    }
}